package com.fr.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.dbutils.ResultSetHandler;
import com.fr.model.Book;

public class BookDao extends BaseDao  {
	public Boolean addBook(Book book) {
		try {
			String sql = "insert into book" + 
					"  (id, service_id, booktime, price, message)" + 
					" values" + 
					"  ((select nvl(max(id),0)" + 
					"		from book)+1, ?, ?, ?, ?)";
			return queryRunner.execute(sql,
						book.getService().getService_id(),
						book.getBookTime(),
						book.getPrice(),
						book.getMessage()
					)==1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public int getId() {
		try {
			String sql = "select nvl(max(id),-1) id" + 
					" from book";
			return queryRunner.query(sql,new ResultSetHandler<Integer>() {
				@Override
				public Integer handle(ResultSet rs) throws SQLException {
					if(rs.next()) {
						return rs.getInt("id");
					}
					return null;
				}
			});
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}

	public long getPrice(int service_id) {
		try {
			String sql = "select price "
					+ " from service "
					+ " where service_id = ?";
			return queryRunner.query(sql,new ResultSetHandler<Long>() {
				@Override
				public Long handle(ResultSet rs) throws SQLException {
					if(rs.next()) {
						return rs.getLong("price");
					}
					return null;
				}
			},service_id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
}